"use strict";
/* Controllers */
app.controller("resolvegroupAddController", ['$scope', '$q', '$location', '$rootScope', '$routeParams', 'resolvegroupAddService', function ($scope, $q, $location, $rootScope, $routeParams, resolvegroupAddService) {

    var vm = $scope.vm = {};
    vm.p = {};
    vm.p.type = $routeParams.type;
    if(vm.p.type=='code') {
        vm.p.resolvegroupId = $routeParams.id; // 如果id!=0为更新
    }else {
        vm.p.id = $routeParams.id; // 如果id!=0为更新
    }
    vm.p.ctiIds = '-';


    var errorFn = function (result) {
        alert(result);
    };

    $scope.addResolvegroup = function () {
        var vm = $scope.vm;
        var params = vm.p;

        var procFn = function (response) {
            if (response.success && response.data) {
                alert("执行成功！")
            } else {
                alert(response.msg);
            }
        };
        return resolvegroupAddService.addResolvegroup(params, procFn, errorFn);
    };

    //$scope.fnRmg = function () {
    //    // var isRmg = $scope.relateMonitorGroup
    //    $scope.vm.p.monitorGroupKey = '';
    //    // $scope.vm.p.users=''
    //    // $('#users').tagsinput('removeAll');
    //};

    var substringMatcher = function (strs) {
        return function findMatches(q, cb) {
            var matches, substringRegex;

            // an array that will be populated with substring matches
            matches = [];

            // regex used to determine if a string contains the substring `q`
            var substrRegex = new RegExp(q, 'i');

            // iterate through the pool of strings and for any string that
            // contains the substring `q`, add it to the `matches` array
            $.each(strs, function (i, str) {
                if (substrRegex.test(str)) {
                    matches.push(str);
                }
            });

            cb(matches);
        };
    };

    var initSugUserIds = function () {
        var vm = $scope.vm;
        var params = {};
        var procFn = function (response) {
            console.log('listUser');
            var data = response.data;
            if (data == null) return;
            var ugn = data.map(function (x) {
                return x.userName
            });

            $('#users').tagsinput({
                typeaheadjs: [{
                    minLength: 0
                }, {
                    name: 'ugiSource',
                    source: substringMatcher(ugn)
                }],
                freeInput: false
            });

            $('#masters').tagsinput({
                typeaheadjs: [{
                    minLength: 0
                }, {
                    name: 'ugiSource',
                    source: substringMatcher(ugn)
                }],
                freeInput: false
            });
        };
        return resolvegroupAddService.listUser(params, procFn, errorFn);
    };

    var initSugCtiIds = function () {
        var vm = $scope.vm;
        var params = {};
        var procFn = function (response) {
            console.log('initSugCtiIds')
            var data = response.data;
            if (data == null) return;

            $('#ctiIds').tagsinput({
                itemValue: 'ctiId',
                itemText: 'ctiName',
                typeaheadjs: [{
                    minLength: 0
                }, {
                    name: 'ctiName',
                    displayKey: 'ctiName',
                    source: substringMatcherObj(data, "ctiName"),
                    limit: 20
                }],
                freeInput: false
            });

            if (typeof (vm.p.ctiIds) == 'undefined' || vm.p.ctiIds == '') {
                return
            }
            var ctiIdArr = vm.p.ctiIds.split(',')
            ctiIdArr.forEach(function (x) {
                var label = data.find(function (y) {
                    return y.ctiId.toString() == x
                })
                if (typeof (label) != 'undefined') {
                    $('#ctiIds').tagsinput('add', label)
                }
            })

        };

        return resolvegroupAddService.listCti(params, procFn, errorFn);
    }

    var substringMatcherObj = function (dataObjs, toMatchKey) {
        return function findMatches(q, cb) {
            var matches, substringRegex;

            // an array that will be populated with substring matches
            matches = [];

            // regex used to determine if a string contains the substring `q`
            var substrRegex = new RegExp(q, 'i');

            // iterate through the pool of strings and for any string that
            // contains the substring `q`, add it to the `matches` array
            $.each(dataObjs, function (i, dataObj) {
                if (substrRegex.test(dataObj[toMatchKey])) {
                    matches.push(dataObj);
                }
            });

            cb(matches);
        };
    };

    $scope.getResolvegroup = function () {
        var vm = $scope.vm;
        var params = {
            id: vm.p.id,
            resolvegroupId: vm.p.resolvegroupId
        };
        var procFn = function (response) {
            if (response.success && response.data) {
                vm.p = (response.data);
                if (vm.p.monitorGroupKey != '') {
                    $scope.relateMonitorGroup = true
                }
            } else {
                alert(response.msg);
            }
        };
        return resolvegroupAddService.getResolvegroup(params, procFn, errorFn);
    };

    if (vm.p.id != 0) {
        console.log(vm.p.id);
        $q.all([$scope.getResolvegroup()]).then(function () {
            initSugUserIds()
            initSugCtiIds()
        })
    } else {
        initSugUserIds()
        initSugCtiIds()
    }
}]);


/* Services */
app.service('resolvegroupAddService', ['ajaxService', function (ajaxService) {

    this.addResolvegroup = function (resolvegroups, successFunction, errorFunction) {
        return ajaxService.AjaxPost(resolvegroups, "/star/api/onduty-app-service/v1/resolvegroup/addResolvegroup.do", successFunction, errorFunction);
    };

    this.getResolvegroup = function (resolvegroups, successFunction, errorFunction) {
        return ajaxService.AjaxPost(resolvegroups, "/star/api/onduty-app-service/v1/resolvegroup/getResolvegroup.do", successFunction, errorFunction);
    };

    this.listUser = function (params, successFunction, errorFunction) {
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/user/user_list.do", successFunction, errorFunction);
    };

    this.listCti = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/onduty-app-service/v1/cti/listCti.do", successFunction, errorFunction);
    };

}]);